<?php

namespace api\controller;

// +----------------------------------------------------------------------
// | User控制层
// +----------------------------------------------------------------------

use common\controller\VerifyController;
use common\exception\LogicException;
use common\service\TransactionService;
use common\service\UserService;
use think\Request;

class UserController extends VerifyController
{
    /**
     * @var \common\service\UserService
     */
    protected $userService;

    public function __construct()
    {
        parent::__construct();
        $this->userService = new UserService();
    }

    /**
     * 获取自己用户信息
     * @param Request $request
     * @return \think\Response
     */
    public function getMyUserInfo(Request $request)
    {
        try {
            $resData = $this->userService->getInfo($request->getUserId(), $request->getTenantId());
            return json(success_response('User information obtained successfully.', $resData));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 获取其它用户信息
     * @param Request $request
     * @return \think\Response
     */
    public function getOtherUserInfo(Request $request)
    {
        try {
            $param = $request->param();
            $hide = !(!empty($param['hide']) && $param['hide'] === 'no');
            $resData = $this->userService->getOtherUserInfo($param['user_id'], $hide);
            return json(success_response('User information obtained successfully.', $resData));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 获取租户通讯录
     * @param Request $request
     * @return \think\Response
     * @throws \Throwable
     */
    public function getAddressList(Request $request)
    {
        $param = $request->param();
        $resData = $this->userService->getDepartmentTree($param['tenant_id']);
        return json(success_response('Get tenant address book successfully.', $resData));
    }

    /**
     * 获取用户列表
     * @param Request $request
     * @return \think\Response
     */
    public function selectUser(Request $request)
    {
        try {
            $param = $request->param();
            $resData = $this->userService->selectUser($param['param']);
            return json(success_response('Get user list successfully.', $resData));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }


    /**
     * 用户注册
     * @param Request $request
     * @return \think\Response
     * @throws \think\Exception
     */
    public function register(Request $request)
    {
        try {
            $resData = $this->userService->register($request->param());
            return json(success_response('Successfully registered user.', $resData));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }


    /**
     * 后台添加用户（同时上传头像）
     * @param Request $request
     * @return \think\Response
     */
    public function addUserWithMedia(Request $request)
    {
        $resData = $this->userService->addUserWithMedia($request->param());
        return json(success_response('Background successfully added user.', $resData));
    }

    /**
     * 修改用户信息（同时修改头像）
     * @param Request $request
     * @return \think\Response
     * @throws \Exception
     */
    public function modifyUserWithMedia(Request $request)
    {
        $resData = $this->userService->modifyUserWithMedia($request->param());
        return json(success_response('Background successfully modify user.', $resData));
    }

    /**
     * 修改当前用户密码
     * @param Request $request
     * @return \think\Response
     */
    public function modifyCurrentUserPassword(Request $request)
    {
        try {
            $resData = $this->userService->modifyUserPassword($request->getUserId(), $request->param());
            return json(success_response('User password modified successfully.', $resData));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 删除指定用户信息
     * @param Request $request
     * @return \think\Response
     */
    public function deleteUser(Request $request)
    {
        try {
            $param = $request->param();
            $resData = $this->userService->deleteUser($param['param']);
            return json(success_response('The specified user was successfully deleted.', $resData));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 切换用户激活状态
     * @param Request $request
     * @return \think\Response
     */
    public function switchActiveUser(Request $request)
    {
        try {
            $param = $request->param();
            $resData = $this->userService->switchActiveUser($param['param']);
            return json(success_response('The specified user was activated successfully.', $resData));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 获得其他用户信息 list
     * @param Request $request
     * @return \think\Response
     * @throws \Throwable
     */
    public function getOtherUsersInfo(Request $request)
    {
        $param = $request->param();
        $tenantId = $param['param']['tenant_id'] ?? 0;
        $resData = $this->userService->getOtherUsersInfo($param['param'], $tenantId);
        return json(success_response('The specified users was activated successfully.', $resData));
    }

    /**
     * 查询指定租户的余额
     * @param Request $request
     * @return \think\Response
     */
    public function getTenantBalance(Request $request)
    {
        $param = $request->param();
        $transactionService = new TransactionService();
        $resData = $transactionService->getTenantBalance($param['tenant_id']);
        return json(success_response('', ['balance' => $resData]));
    }

    /**
     * 通过银行转账充值
     * @param Request $request
     * @return \think\Response
     */
    public function rechargeByBankTransfer(Request $request)
    {
        try {
            $param = $request->param();
            $transactionService = new TransactionService();
            $resData = $transactionService->rechargeByBankTransfer($param['data']);
            return json(success_response('Bank transfer record added successfully.', $resData));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 财务确认充值
     * @param Request $request
     * @return \think\Response
     * @throws \Exception
     */
    public function confirmRecharge(Request $request)
    {
        try {
            $param = $request->param();
            $transactionService = new TransactionService();
            $resData = $transactionService->confirmRecharge($param['recharge_id']);
            return json(success_response('Bank transfer record added successfully.', $resData));
        } catch (LogicException $e) {
            throw_strack_exception($e->getMessage(), $e->getCode());
        }
    }

    /**
     * 订单扣款
     * @param Request $request
     * @return \think\Response
     * @throws \Exception
     */
    public function orderDeduction(Request $request)
    {
        $transactionService = new TransactionService();
        $resData = $transactionService->orderDeduction($request->param());
        return json(success_response('Order deduction succeeded.', $resData));
    }

    /**
     * 订单打款
     * @param Request $request
     * @return \think\Response
     */
    public function orderIncrease(Request $request)
    {
        $transactionService = new TransactionService();
        $resData = $transactionService->orderIncrease($request->param());
        return json(success_response('Order increase succeeded.', $resData));
    }

    /**
     * 查询系统用户信息
     * @param Request $request
     * @return \think\Response
     */
    public function selectSystemUser(Request $request)
    {
        $tenantId = $request->param()['param']['tenant_id'] ?? $request->getTenantId();
        $res = $this->userService->selectSystemUser($request->param()['param'], $tenantId);
        return json(success_response("OK", $res));
    }

    /**
     * 普通用户查询
     * @param Request $request
     * @return \think\Response
     * @throws \Exception
     */
    public function selectNormalUser(Request $request)
    {
        $res = $this->userService->selectNormalUser($request->param()['param']);
        return json(success_response("OK", $res));
    }

    /**
     * 获取当前用户的部门
     * @param Request $request
     * @return \think\Response
     */
    public function getCurrentDepartment(Request $request)
    {
        $tenantId = $request->getTenantId();
        $param = $request->param();
        $userId = $param['param']['filter']['user_id'];
        $res = $this->userService->getCurrentDepartment($tenantId, $userId);
        return json(success_response("OK", $res));
    }

    /**
     * 获取部门及其用户的信息
     * @param Request $request
     * @return \think\Response
     * @throws \Throwable
     */
    public function getChildrenDepartmentUser(Request $request)
    {
        $param = $request->param();
        $tenantId = $param['param']['filter']['tenant_id'] ?? $request->getTenantId();
        $includeEmployed = $request->param()['param']['include_employed'] ?? 'no';
        if (empty($param['param']['filter']['specify_role'])) {
            $res = $this->userService->getChildrenDepartmentUser($tenantId, $param['param'], $includeEmployed === 'yes');
        } else {
            $res = $this->userService->getSpecifyRoleUser($tenantId, $param['param'], $includeEmployed === 'yes');
        }
        return json(success_response("OK", $res));
    }

    /**
     * 获取用户的群组
     * @param Request $request
     * @return \think\Response
     */
    public function getCurrentChatGroup(Request $request)
    {
        $param = $request->param();
        $res = $this->userService->getCurrentChatGroup($param['param']['filter']['user_id']);
        return json(success_response("OK", $res));
    }

    /**
     * 常用联系人
     * @param Request $request
     * @return \think\Response
     * @throws \Throwable
     */
    public function frequentContacts(Request $request)
    {
        $param = $request->param();
        $filter = $param['param']['filter'];
        $limit = $param['param']['limit'] ?? 50;
        $res = $this->userService->frequentContacts($filter, $request->getUserId(), $limit);
        return json(success_response("OK", $res));
    }

    /**
     * 注销用户后离开聊天会话
     * @param Request $request
     * @return \think\Response
     * @throws \Exception
     */
    public function switchActiveUserChat(Request $request)
    {
        $param = $request->param();
        $isActive = $param['param']['filter']['is_active'];
        $res = $this->userService->switchActiveUserChat($isActive, $request->getUserId());
        return json(success_response("OK", $res));
    }

    /**
     * 通过手机号,获取用户id
     * @param Request $request
     * @return \think\Response
     * @throws \Exception
     */
    public function getUserId(Request $request)
    {
        $param = $request->param();
        $res = $this->userService->getUserId($param['data']);
        return json(success_response("OK", $res));
    }

    /**
     * 搜索公司集团用户
     * @param Request $request
     * @return \think\Response
     */
    public function searchTenantUser(Request $request)
    {
        $param = $request->param();
        $tenantId = $param['param']['filter']['tenant_id'] ?? $request->getTenantId();
        $includeEmployed = $request->param()['param']['include_employed'] ?? 'no';

        $res = $this->userService->searchTenantUser($tenantId, $param['param'],$includeEmployed==='yes');
        return json(success_response("OK", $res));
    }
}
